package solver;


import io.*;
import structure.*;

public class solver extends Thread implements ICellEventListener {
	
	public volatile boolean stop = false;
	
	private grid _grid;
	private textEngine _t;
	
	public solver(grid g) {
		_grid = g;
		_t = new textEngine(_grid);
		
		for (int r = 0; r < 9; r++) {
			for (int c = 0; c < 9; c++) {
				g.getCell(r, c).subscribe(this);
			}
		}
	}
	
	public boolean isSolved() {
		boolean _solved = true;
		
		for (int r = 0; r < 9; r++) {
			for (int c = 0; c < 9; c++) {
				if (_grid.getCell(r, c).getValue() == 0 ) { _solved = false; }
			}
		}
		return _solved;
	}
	
	public void run() {
		String state1 = _t.toStringState();
		
		System.out.println( "Solver starting." );
		
		
		//put solve check here
		while (!stop) {
			//System.out.println( "Thread is running..." );
			//long time = System.currentTimeMillis();
			//while ( (System.currentTimeMillis()-time < 1000) && (!stop) ) {
			
			//this is the individual rule check
			while (!stop) {
				for (cell c : _grid.getRow(0)) {
					c.removePossible(7);
					c.removePossible(8);
					c.removePossible(9);
				}
			}
			
			
			
			
		
			String state2 = _t.toStringState();
			
			if (isSolved()) { System.out.println("Solved!"); stop = true; break; }
			//no change!
			if (state1.equals(state2)) { System.out.println("Stumped!"); stop = true; break; }
		}
		System.out.println( "Solver ended." );
		
	}

	public void quit() {
		System.out.println( "Solver stopping." );
		stop = true;
	}

	@Override
	public void handleEventCellChanged(cell e) {
		this.quit();
		
		//recursive call!
		this.run();
	}

}
